package mm.chenchen.modules.file.service.impl;

import mm.chenchen.common.utils.FileUtils;
import mm.chenchen.common.utils.MinioClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Component
public class FileService {
    @Autowired
    private MinioClientUtil minioClientUtil;

    public void downLoadFromMinio(String bucket, String fileName, Long opserId, HttpServletResponse response) {
        InputStream inputStream = FileUtils.downloadFromMinio(minioClientUtil.getMinioClient(), fileName, bucket);

        HttpHeaders headers = new HttpHeaders();// http协议
        headers.setContentDispositionFormData("attachment", fileName);
        BufferedInputStream br = new BufferedInputStream(inputStream);
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        response.setCharacterEncoding("UTF-8");

        response.setHeader("conent-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName.split("/")[fileName.split("/").length-1], "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Access-Control-Allow-Origin", "*");
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            br.close();
            out.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
